<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @cell-mouse-enter="(m) => m.active=true"
          @cell-mouse-leave="(m) => m.active=false"
          @sort-change="handleSort"
        >
          <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />
          <el-table-column prop="name" label="供应商名称" width="180">
            <template slot-scope="scope">
              <a title="打开报价单" target="_blank" @click="handleShowProduct(scope.row)">{{ scope.row.name }}</a>
            </template>
          </el-table-column>
          <el-table-column prop="type_name" label="企业类型" width="180" />
          <el-table-column prop="tag" label="标签" width="180">
            <template slot-scope="scope">
              <el-tag
                v-for="tag in scope.row.tag"
                :key="tag"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" width="180" />
          <el-table-column prop="contact_name" label="联系人姓名" width="180" />
          <el-table-column prop="contact_phone" label="联系电话" width="180" />
          <el-table-column prop="wechat" label="微信" width="180" />
          <el-table-column prop="wechatgroup" label="微信群名" width="200" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="star" label="星级" width="100" />

          <el-table-column prop="source" label="来源" width="180" />
          <el-table-column prop="url" label="网址" width="180" />
          <el-table-column prop="total_products" label="总产品数" width="120" />
          <el-table-column prop="create_at" label="创建时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.create_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="230">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleImport(scope.row)">导入</el-button>
              <el-button size="mini" type="warning" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="企业类型" prop="type_name">
          <div style="display: flex; align-items: center;">
            <el-select v-model="temp.type_name" style="flex-grow: 0; margin-right: 10px;width: 200px;">
              <el-option value="工厂" label="工厂" />
              <el-option value="贸易公司" label="贸易公司" />
            </el-select>
            <div style="flex-grow: 0;">自定义:</div>
            <el-input v-model="temp.type_name" placeholder="自定义名称" style="flex-grow: 0;width: 200px" />
          </div>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contact_name">
          <el-input v-model="temp.contact_name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="temp.contact_phone" />
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="temp.wechat" />
        </el-form-item>
        <el-form-item label="微信群名" prop="wechatgroup">
          <el-input v-model="temp.wechatgroup" placeholder="请输入微信群名称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" type="textarea" :rows="8" />
        </el-form-item>
        <el-form-item label="星级" prop="star">
          <el-rate v-model="temp.star" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-tag
            v-for="tag in temp.tag"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="temp.source" />
        </el-form-item>
        <el-form-item label="网址" prop="url">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="产品数量" prop="total_products">
          <el-input v-model="temp.total_products" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      title="导入产品"
      :visible.sync="importVisible"
      :close-on-click-modal="false"
    >
      <el-row>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-upload
            ref="upload"
            :headers="headers"
            :action="upload_url"
            :multiple="true"
            drag
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            :before-upload="beforeUpload"
            :data="{id: this.temp.id}"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            multiple
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">过大文件请使用网盘</div>
          </el-upload>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>

        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <span style="display: block">支持的表头参数:</span>
          <span v-for="(item,index) in excel_headers" :key="index" style="margin-left: 5px; margin-right: 5px">{{ item }}</span>
          <el-alert
            title="注意"
            description="粘贴的图片必须每行图片数量相同，如果不足，请复制相同的保持图片数量每行相同!如果使用外部 url 作为图片链接，则不在支持粘贴图片！"
            type="success"
            :closable="false"
          />
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { Get, Post, Put, Delete } from '@/api/crm/crmsupplier'
import qs from 'qs'
import { countries, customer_source, getCountryLabel } from '../../api/crm/crmcommon'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmcustomer',
  data() {
    return {
      fileList: [],
      listObj: {},
      upload_url: '',
      data: [],
      listLoading: false,
      getCountryLabel: getCountryLabel,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      countries: countries,
      customer_sources: customer_source,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      importVisible: false,
      excel_headers: [
        'name',
        'product_category',
        'product_type',
        'our_sku',
        'supplier_sku',
        'images',
        'moq',
        'stock',
        'model',
        'parameters',
        'parameters_en',
        'shop_url',
        'json_fields',
        'pi_lead_period',
        'manufacture_lead_period',
        'note'
      ],
      temp: {
        name: '', // 供应商名称
        type_name: '工厂', // 企业类型
        address: '', // 地址
        contact_name: '', // 联系人名称
        contact_phone: '', // 联系电话
        wechat: '', // 微信号
        wechatgroup: '', // 微信群名
        email: '', // 电子邮箱
        star: 0, // 评级星数
        tag: [], // 标签
        source: '', // 来源
        url: '' // 网址
      },

      width: '',
      innerDialogVisible: false
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  mounted() {
    this.boolUploadSucceed = false
    this.upload_url = process.env.VUE_APP_BASE_API + '/crm/api/crmsupplierfile/'
  },
  created() {
    this.getList()
  },
  methods: {
    beforeUpload(file) {
      const _self = this
      const fileName = file.uid
      console.log(file)
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        _self.listObj[fileName] = { hasSuccess: false, uid: file.uid }
        resolve(true)
      })
    },
    handleInsertFile(item) {
      this.$emit('insert', item)
      this.dialogVisible = false
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    handleSuccess(response, file) {
      if (response.success) {
        this.$notify({
          title: '成功',
          message: `文件${file.name}上传成功`,
          type: 'success',
          duration: 1000
        })
        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = response.data.url
            this.success_data.push(response.data)
            this.listObj[objKeyArr[i]].hasSuccess = true
            return
          }
        }
      } else {
        this.$notify({
          title: '失败',
          message: `文件${file.name}上传失败, ${response.msg}`,
          type: 'error',
          duration: 3000
        })
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleClose(tag) {
      this.temp.tag.splice(this.temp.tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    resetTemp() {
      this.temp = {
        name: '', // 供应商名称
        type_name: '工厂', // 企业类型
        address: '', // 地址
        contact_name: '', // 联系人名称
        contact_phone: '', // 联系电话
        wechat: '', // 微信号
        wechatgroup: '', // 微信群名
        email: '', // 电子邮箱
        star: 0, // 评级星数
        tag: [], // 标签
        source: '', // 来源
        url: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleShowProduct(row) {
      this.$router.push({ name: 'crmsupplierproduct', query: { id: row.id, name: row.name }})
    },
    handleImport(row) {
      this.temp = Object.assign({}, row)
      this.importVisible = true
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新客户资料'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除客户:${row.name}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改客户:${row.name}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
